//
//  FSFirstViewController.m
//  TextPage
//
//  Created by 刘沿 on 16/6/30.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSFirstViewController.h"
#import "GDataDefines.h"

@interface FSFirstViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSArray *dataArray;

@property (nonatomic,strong) UIPickerView *pickView;

@property (nonatomic,strong) UITextField *texfield;

@property (nonatomic,strong) UIToolbar *toolBar;

@property (nonatomic,strong) NSMutableArray *foodArray;

@property (nonatomic,strong) UITableView *tab;

@property(nonatomic,assign)NSInteger currentPage; //当前页

@property(nonatomic,assign)NSInteger totalCounts; //总条数

@property (nonatomic,copy) NSString *dataString;

@end

@implementation FSFirstViewController

-(NSArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)foodArray{
    if (_foodArray == nil) {
        
        _foodArray = [NSMutableArray array];
    }
    return _foodArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    [self setUp];
    
    __weak typeof (self) weakSelf = self;
    [self.tab addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
        
        [weakSelf loadData];
        
    }];
    [self.tab headerBeginRefreshing];
    
    
}

- (void)loadData{

    if(!self.texfield.text.length){
    
        self.texfield.text = @"星期一";
    
        self.dataString = @"0";
    }else if([self.texfield.text isEqualToString:@"星期一"]){
    
        self.dataString = @"0";
    
    }else if ([self.texfield.text isEqualToString:@"星期二"]){
        
        self.dataString = @"1";
    }else if([self.texfield.text isEqualToString:@"星期三"]){
    
        self.dataString = @"2";
    }else if([self.texfield.text isEqualToString:@"星期四"]){
        
        self.dataString = @"3";
    }else if([self.texfield.text isEqualToString:@"星期五"]){
        
        self.dataString = @"4";
    }else if([self.texfield.text isEqualToString:@"星期六"]){
        
        self.dataString = @"5";
    }else if([self.texfield.text isEqualToString:@"星期天"]){
        
        self.dataString = @"6";
    }
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray * array = @[@{@"userId":userId},@{@"sDate":self.dataString},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:Kexchlogistics arrays:array method:KtoselectCanteenPage success:^(id JSON) {
        
        if (self.currentPage == 1) {
            [self.foodArray removeAllObjects];
        }
        
        [self.foodArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        
        [self.tab reloadData];
        
        [self.tab headerEndRefreshing];
    } failure:^(NSError *error) {
        
        
    }];

}

//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSManagerModel * model = [[FSManagerModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            [array addObject:model];
        }
    }
    
    return array;
}


- (void)setUp{
    self.dataArray = @[@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",@"星期天"];
    
    UITextField *textField = [[UITextField alloc] init];
    
    self.texfield = textField;
    
    textField.borderStyle = UITextBorderStyleRoundedRect;
    
    textField.placeholder = @"点击输入查看的日期";
    
    textField.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    textField.textAlignment = NSTextAlignmentCenter;
    
    textField.delegate = self;
    
    [self.view addSubview:textField];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(5);
        
        make.width.equalTo(@300);
        
        make.centerX.equalTo(self.view.mas_centerX);
        
        make.height.equalTo(@40);
        
    }];
    
    UIPickerView *pick = [[UIPickerView alloc] init];
    
    self.pickView = pick;
    
    pick.delegate = self;
    
    pick.dataSource = self;
    
    [self.view addSubview:pick];
    
    [pick mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@200);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(240);
        
    }];
    
    UIToolbar *tobar = [[UIToolbar alloc] init];
    
    self.toolBar = tobar;
    
    tobar.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:tobar];
    
    [tobar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@40);
        
        make.bottom.equalTo(pick.mas_top);
    }];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finishClick)];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    tobar.items = @[spaceItem,rightItem];
    
    UITableView *tab = [[UITableView alloc] init];
    
    tab.delegate = self;
    
    tab.dataSource = self;
    
    self.tab = tab;
    
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(textField.mas_bottom).mas_offset(10);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-20);
    }];
}

- (void)finishClick{
    
    [self loadData];
    
    self.tab.hidden = NO;
    
    [self.pickView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@200);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(240);
        
    }];
   
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    return self.dataArray.count;

}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    return self.dataArray[row];

}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
   
    return 60;

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    self.texfield.text = self.dataArray[row];

}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    self.tab.hidden = YES;
    
    // 此处编写弹出日期选择器的代码。
    [self.pickView becomeFirstResponder];
    
    [self.pickView mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self.view.mas_left).mas_offset(20);
        
            make.right.equalTo(self.view.mas_right).mas_offset(-20);
            
            make.height.equalTo(@200);
        
            make.bottom.equalTo(self.view.mas_bottom);
            
    }];
    
    return NO;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    self.tab.hidden = NO;
    
    [self.pickView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@200);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(240);
        
    }];

}

#pragma TableView

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.foodArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *reuseId = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];

    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];
    }
    
    FSManagerModel *model = self.foodArray[indexPath.row];
    
    cell.textLabel.text = model.title;
    
    return cell;
}



@end





















